package com.hyacinth.forumbite.controller;

import com.hyacinth.forumbite.common.AppConfig;
import com.hyacinth.forumbite.common.AppResult;
import com.hyacinth.forumbite.common.ResultCode;
import com.hyacinth.forumbite.exception.ApplicationException;
import com.hyacinth.forumbite.model.User;
import com.hyacinth.forumbite.service.UserService;
import com.hyacinth.forumbite.utils.MD5Util;
import com.hyacinth.forumbite.utils.StringUtil;
import com.hyacinth.forumbite.utils.UUIDUtil;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.Parameters;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpSession;
import lombok.NonNull;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.*;

/**
 * @Author: Yun
 * @Date: 2025/4/28
 */
@Slf4j
@RestController
@RequestMapping("/user")
@Tag(name = "用户相关接口")
public class UserController {
    private final UserService userService;

    public UserController(UserService userService) {
        this.userService = userService;
    }

    @Operation(summary = "登录")
    @PostMapping("/login")
    @Parameters({
            @Parameter(name = "username", description = "用户名"),
            @Parameter(name = "password", description = "密码")
    })
    public AppResult login(@RequestParam("username") @NonNull String username, @RequestParam("password") @NonNull String password,
                           HttpServletRequest request) {
        User user = userService.login(username, password);
        if (user == null) {
            log.warn(ResultCode.FAILED_LOGIN.toString());
            return AppResult.failed(ResultCode.FAILED_LOGIN);
        }
        // 获取与当前 HTTP 请求相关的会话（Session）对象
        // 如果 当前请求没有对应的会话，就会创建一个新的会话
        HttpSession session = request.getSession(true);
        session.setAttribute(AppConfig.USER_SESSION, user);

        return AppResult.success();
    }

    @Operation(summary = "注册")
    @PostMapping("/register")
    @Parameters({
            @Parameter(name = "username", description = "用户名"),
            @Parameter(name = "nickname", description = "昵称"),
            @Parameter(name = "password", description = "密码"),
            @Parameter(name = "passwordRepeat", description = "重复密码")
    })
    public AppResult register(@RequestParam("username") @NonNull String username, @RequestParam("nickname") @NonNull String nickname,
                              @RequestParam("password") @NonNull String password, @RequestParam("passwordRepeat") @NonNull String passwordRepeat) {
        if (StringUtil.isEmpty(username) || StringUtil.isEmpty(nickname)
                || StringUtil.isEmpty(password) || StringUtil.isEmpty(passwordRepeat)) {
            return AppResult.failed(ResultCode.FAILED_PARAMS_VALIDATE);
        }
        if (!password.equals(passwordRepeat)) {
            log.info(ResultCode.FAILED_TWO_PWD_NOT_SAME.toString());
            return AppResult.failed(ResultCode.FAILED_TWO_PWD_NOT_SAME);
        }
        // 构造user对象
        String salt = UUIDUtil.UUID_32();
        String encryptPassword = MD5Util.md5Salt(password, salt);
        User user = new User()
                .setUsername(username)
                .setPassword(encryptPassword)
                .setNickname(nickname).setSalt(salt);
        userService.createNormalUser(user);
        return AppResult.success();
    }

    @Operation(summary = "获取用户信息")
    @Parameters({
            @Parameter(name = "id", description = "id")
    })
    @GetMapping("/info")
    public AppResult<User> getUserInfo(HttpServletRequest request, @RequestParam(value = "id", required = false) Long id) {
        // 当id为空.从session中获取id
        if (id == null) {
            HttpSession session = request.getSession(false);
            if (session == null || session.getAttribute(AppConfig.USER_SESSION) == null) {
                return AppResult.failed(ResultCode.FAILED_FORBIDDEN);
            }
            User user = (User) session.getAttribute(AppConfig.USER_SESSION);
            return AppResult.success(user);
        }
        // 如果不为空,从数据库查询
        User user = userService.selectById(id);
        if (user == null) {
            return AppResult.failed(ResultCode.FAILED_USER_NOT_EXISTS);
        }
        return AppResult.success(user);
    }

    @Operation(summary = "退出登录")
    @GetMapping("/logout")
    public AppResult logout(HttpServletRequest request) {
        HttpSession session = request.getSession(false);
        if (session != null) {
            log.info("退出登录");
            // 销毁session
            session.invalidate();
        }
        return AppResult.success("退出成功");
    }

    @Operation(summary = "修改个人信息")
    @Parameters({
            @Parameter(name = "username", description = "用户名"),
            @Parameter(name = "nickname", description = "昵称"),
            @Parameter(name = "gender", description = "性别"),
            @Parameter(name = "email", description = "邮箱"),
            @Parameter(name = "phonenum", description = "电话号码"),
            @Parameter(name = "remark", description = "个人简介"),
    })
    @PostMapping("/modifyInfo")
    public AppResult<User> modifyInfo(HttpServletRequest request,
                                      @RequestParam(value = "username", required = false) String username,
                                      @RequestParam(value = "nickname", required = false) String nickname,
                                      @RequestParam(value = "gender", required = false) Byte gender,
                                      @RequestParam(value = "email", required = false) String email,
                                      @RequestParam(value = "phoneNum", required = false) String phonenum,
                                      @RequestParam(value = "remark", required = false) String remark) {
        HttpSession session = request.getSession(false);
        User user = (User) session.getAttribute(AppConfig.USER_SESSION);

        user.setUsername(username)
                .setNickname(nickname)
                .setGender(gender)
                .setEmail(email)
                .setPhoneNum(phonenum)
                .setRemark(remark);
        userService.modifyInfo(user);

        user = userService.selectById(user.getId());
        session.setAttribute(AppConfig.USER_SESSION, user);
        return AppResult.success(user);
    }

    @Operation(summary = "修改密码")
    @Parameters({
            @Parameter(name = "newPassword", description = "新密码"),
            @Parameter(name = "oldPassword", description = "旧密码"),
            @Parameter(name = "passwordRepeat", description = "确认密码")
    })
    @PostMapping("/modifyPwd")
    public AppResult modifyPassword(HttpServletRequest request,
                                    @RequestParam("oldPassword") @NonNull String oldPassword,
                                    @RequestParam("newPassword") @NonNull String newPassword,
                                    @RequestParam("passwordRepeat") @NonNull String passwordRepeat) {
        if (!newPassword.equals(passwordRepeat)) {
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED));
        }
        HttpSession session = request.getSession(false);
        User user = (User) session.getAttribute(AppConfig.USER_SESSION);
        userService.modifyPwd(user.getId(), newPassword, oldPassword);
        session.invalidate();
        return AppResult.success();
    }
}
